package com.wandian.news.mvvm.toutiao.toutiaodetails;

import android.animation.ValueAnimator;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mylib.libcore.AppContext;
import com.mylib.libcore.config.RouterConfig;
import com.mylib.libcore.mvvm.BaseMVVMActivity;
import com.mylib.libcore.tools.CSJADTools;
import com.mylib.libcore.tools.GDTADTools;
import com.mylib.libcore.tools.TTAdManagerHolder;
import com.mylib.libcore.utils.StatusBarUtils;
import com.mylib.libcore.utils.StrUtil;
import com.mylib.libcore.utils.StringUtil;
import com.mylib.libcore.utils.ToastUtil;
import com.mylib.libcore.utils.UIUtils;
import com.mylib.widget.CustomCoinToast;
import com.mylib.widget.ProgressWebView;
import com.wandian.news.R;
import com.wandian.news.adapter.TouTiaoDetailsRecycleAdapter;
import com.wandian.news.databinding.NewsActivityToutiaoDetailBinding;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.bytedance.sdk.openadsdk.TTRewardVideoAd;

import static com.mylib.libcore.config.AppConfig.CSJ_BANNER_ONE_ID;
import static com.mylib.libcore.config.AppConfig.CSJ_ZX_ID;
import static com.mylib.libcore.config.AppConfig.GDT_APP_MB_PIC_TWO;


/**
 * @author Administrator
 * @date 2019/12/18-14:28
 * @description 头条详情
 **/
@Route(path = RouterConfig.ROUTER_ACTIVITY_NEWS_TOUTIAO_DETAIL)
public class TouTiaoDetailActivity extends BaseMVVMActivity<TouTiaoDetailActivityViewModel> implements BaseQuickAdapter.RequestLoadMoreListener , TouTiaoDetailsRecycleAdapter.ItemDataClink {
    private NewsActivityToutiaoDetailBinding dataBinding;
    private String newsID;
    private String htmlString = "";
    private TouTiaoDetailsRecycleAdapter touTiaoChildRecycleAdapter;
    private ProgressWebView webView;
    private TextView tv_ckqw,tv_item_news_title,tv_item_news_time;
    private RelativeLayout rl_ad_top;
    private FrameLayout fl_ad_top;
    private int page =1;
    private String value = "guonei";
    private String news_form_time = "";
    private String newsTitle;
    private String newsDescribe;
    private int oldScrollY=0;
    private TTAdNative mTTAdNative;

    private int scrollNum = 0;//已加载进度
    private int scrollMaxNum = 3;//最大进度
    private int scrollStartY = 0;//动画开始进度
    private int scrollEndY = 0;//动画结束进度
    private boolean isMoving = false;//是否滚动
    private boolean isSubmitTask = false;//是否提交任务
    //看视频
    private TTRewardVideoAd mRewardVideoAd;
    private boolean videoPrepare = false;


    @Override
    public void init(Bundle savedInstanceState) {
        dataBinding = DataBindingUtil.setContentView(this, R.layout.news_activity_toutiao_detail);
        dataBinding.setLifecycleOwner(this);
        dataBinding.setViewModel(mViewModel);

        Bundle bundle = getIntent().getExtras();
        if(!UIUtils.isEmpty(bundle)){
            newsID = bundle.getString("newsID");
            newsTitle =  bundle.getString("newsTitle");
            newsDescribe =  bundle.getString("newsDescribe");
            String type = getIntent().getStringExtra("value");
            if(!UIUtils.isEmpty(type))value = type;
        }
        initViewData();
        initClink();
        initRecycleView();
        getNewsDetailsById();

        if(AppContext.getInstance().getAppPreferencesHelper().getSubmitTaskNum()%5==4){
            dataBinding.circularProgressView.setVisibility(View.GONE);
            Glide.with(this).load(R.drawable.img_video_spz).into(dataBinding.ivSpz);
            dataBinding.ivSpz.setVisibility(View.VISIBLE);
        }else {
            dataBinding.circularProgressView.setVisibility(View.VISIBLE);
            dataBinding.ivSpz.setVisibility(View.GONE);
        }
    }

    private void getUrlContent(){
        tv_item_news_title.setText(newsTitle+"");
        tv_item_news_time.setText( ""+news_form_time);
        new Thread(new Runnable() {
            @Override
            public void run() {
                String res=null;
                try {
                    URL url = new URL(newsID);
                    HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                    //设置超时间为3秒
                    conn.setConnectTimeout(15*1000);
                    //防止屏蔽程序抓取而返回403错误
                    conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
                    //得到输入流
                    InputStream inputStream = conn.getInputStream();
                    res = readInputStream(inputStream);
                    Log.d("urlurl",newsID+"=="+res);
                    if(!UIUtils.isEmpty(res) && res.length()>4){
                        String[] split_div = res.split("</div>");
                        String[] content_ids =  {""};
                        String content_key_ids =  AppContext.getInstance().getAppPreferenceForever().getNewsDetailsKeyID()+"";
                        Log.d("content_key_id",content_key_ids+"");
                       if(!UIUtils.isEmpty(content_key_ids) &&content_key_ids.length()>4)content_ids = content_key_ids.split(";");
                       boolean haveContent = false;
                       for(String item:content_ids){
                           if(!UIUtils.isEmpty(item) && res.contains(item)){//js_article_content"
                               haveContent =true;
                               for(int i=0;i<split_div.length;i++){
                                   if(!UIUtils.isEmpty(split_div[i]) && split_div[i].contains(item)){
                                       String text =split_div[i]+"";
                                       htmlString=text.substring(split_div[i].indexOf("<p>"));
                                       //      Log.d("UrlTools",htmlString+"");
                                       runOnUiThread(new Runnable() {
                                           @Override
                                           public void run() {
                                               if(!UIUtils.isEmpty(htmlString)){
                                                   if (StrUtil.isUrl(htmlString)){
                                                       webView.loadUrl(htmlString);
                                                   } else{
                                                       webView.loadDataWithBaseURL(null, getHtmlData(htmlString), "text/html", "utf-8", null);
                                                   }
                                               }
                                           }
                                       });
                                   }

                               }

                           }
                       }
                       if(!haveContent){
                           Bundle bundle = new Bundle();
                           bundle.putString("url",newsID);
                           bundle.putString("title",newsTitle);
                           bundle.putString("type","微信头条");
                           ARouter.getInstance().build(RouterConfig.ROUTER_ACTIVITY_WEB).with(bundle).navigation();
                       }
                    }

                } catch (Exception e) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Bundle bundle = new Bundle();
                            bundle.putString("url",newsID);
                            bundle.putString("title",newsTitle);
                            bundle.putString("type","微信头条");
                            ARouter.getInstance().build(RouterConfig.ROUTER_ACTIVITY_WEB).with(bundle).navigation();
                        }
                    });
                }
            }
        }).start();
    }

    /**
     * 从输入流中获取字符串
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static String readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return new String(bos.toByteArray(),"utf-8");
    }

    private void getNewsDetailsById(){
        scrollNum = 0;//已加载进度
        scrollMaxNum = 3;//最大进度
        scrollStartY = 0;//动画开始进度
        scrollEndY = 0;//动画结束进度
        isMoving = false;//是否滚动
        isSubmitTask = false;//是否提交任务
        initCSJAD();
        getUrlContent();
        getNewsPageData(true);
    }


    /**
     * 初始化穿山甲广告
     */
    private void initCSJAD(){
        try{
            TTAdManagerHolder.init(TouTiaoDetailActivity.this);
            mTTAdNative = TTAdManagerHolder.getTTAdNative(TouTiaoDetailActivity.this);
            mTTAdNative.loadRewardVideoAd(CSJADTools.getAdSlot("浏览奖励",1,"news"),
                    new TTAdNative.RewardVideoAdListener() {
                        @Override
                        public void onError(int i, String s) {
                            videoPrepare = false;
                        }

                        @Override
                        public void onRewardVideoAdLoad(TTRewardVideoAd ttRewardVideoAd) {
                            videoPrepare = false;
                            if(UIUtils.isEmpty(ttRewardVideoAd))return;
                            mRewardVideoAd = ttRewardVideoAd;
                        }

                        @Override
                        public void onRewardVideoCached() {
                            videoPrepare = true;
                        }
                    });
            final AdSlot adSlot = new AdSlot.Builder()
                    .setCodeId(CSJ_ZX_ID)
                    .setSupportDeepLink(true)
                    .setExpressViewAcceptedSize(360+20,90) //期望模板广告view的size,单位dp
                    .setImageAcceptedSize(120, 90)
                    .setAdCount(3)
                    .build();
            //加载广告
            //step5:请求广告，调用feed广告异步请求接口，加载到广告后，拿到广告素材自定义渲染
            //step5:请求广告，对请求回调的广告作渲染处理
            if(!UIUtils.isEmpty(mTTAdNative)){
                mTTAdNative.loadNativeExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
                    @Override
                    public void onError(int code, String message) {
                        Log.d("loadCSJAdMiddle","message====="+message);
                    }

                    @Override
                    public void onNativeExpressAdLoad(List<TTNativeExpressAd> ads) {
                        if (ads == null || ads.isEmpty()) {
                            return;
                        }
                        if(!UIUtils.isEmpty(touTiaoChildRecycleAdapter)){
                            for(TTNativeExpressAd ad : ads){
                                touTiaoChildRecycleAdapter.getAds().add(ad);
                            }
                            if(!UIUtils.isEmpty(touTiaoChildRecycleAdapter.getData()) && touTiaoChildRecycleAdapter.getData().size()>0){
                                touTiaoChildRecycleAdapter.notifyDataSetChanged();
                            }
                        }
                    }
                });
            }
        }catch (Exception e){

        }
    }

    /**
     * 准备视频
     */
    private void prepareVideo(){
        if (mRewardVideoAd != null && videoPrepare) {
            mRewardVideoAd.setRewardAdInteractionListener(new TTRewardVideoAd.RewardAdInteractionListener() {

                @Override
                public void onAdShow() {
                    Log.d("VideoAd","onAdShow");
                    //   Toast.makeText(RewardVideoActivity.this, "rewardVideoAd show", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onAdVideoBarClick() {
                    Log.d("VideoAd","onAdVideoBarClick");
                    //  Toast.makeText(RewardVideoActivity.this, "rewardVideoAd bar click", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onAdClose() {
                    Log.d("VideoAd","onAdClose");
                    //   Toast.makeText(RewardVideoActivity.this, "rewardVideoAd close", Toast.LENGTH_SHORT).show();
                    mRewardVideoAd = null;
                    CustomCoinToast.showToast(TouTiaoDetailActivity.this,"视频奖励","1金币");
                }

                @Override
                public void onVideoComplete() {
                    Log.d("VideoAd","onVideoComplete");
                    // Toast.makeText(RewardVideoActivity.this, "rewardVideoAd complete", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onVideoError() {
                    Log.d("VideoAd","onVideoError");
                }

                @Override
                public void onRewardVerify(boolean b, int i, String s, int i1, String s1) {

                }
//
//                @Override
//                public void onRewardVerify(boolean b, int i, String s, int i1, String s1) {
//                    Log.d("VideoAd","onRewardVerify"+s+"=="+s1);
//                }

                @Override
                public void onSkippedVideo() {
                    Log.d("VideoAd","onSkippedVideo");
                }
            });
            //展示广告，并传入广告展示的场景
            mRewardVideoAd.showRewardVideoAd(TouTiaoDetailActivity.this, TTAdConstant.RitScenes.CUSTOMIZE_SCENES, "scenes_test");
        } else {
            ToastUtil.show("视频资源准备中，请稍后再试");
        }
    }

    private void getNewsPageData(boolean isReflsh){
        if(isReflsh){
            page =1;
            if(!UIUtils.isEmpty(touTiaoChildRecycleAdapter) && !UIUtils.isEmpty(touTiaoChildRecycleAdapter.getData())){
                touTiaoChildRecycleAdapter.getData().clear();
                touTiaoChildRecycleAdapter.notifyDataSetChanged();
            }
        }else {
            page++;
        }
        mViewModel.getContentData(value,page,isReflsh);
    }

    private void reflashData(){
        if(!UIUtils.isEmpty(webView)) webView.removeAllViews();
        if(!UIUtils.isEmpty(touTiaoChildRecycleAdapter)){
            touTiaoChildRecycleAdapter.getData().clear();
            dataBinding.recyclerChild.removeAllViews();
        }
        initClink();
        initRecycleView();
        getNewsDetailsById();
        initViewData();
    }

    private void initRecycleView(){

        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getContext());
        dataBinding.recyclerChild.setLayoutManager(layoutManager);
        touTiaoChildRecycleAdapter  = new TouTiaoDetailsRecycleAdapter(R.layout.news_item_zixun_style_one,newsID);
        dataBinding.recyclerChild.setAdapter(touTiaoChildRecycleAdapter);

        touTiaoChildRecycleAdapter.setOnLoadMoreListener(this, dataBinding.recyclerChild);
        View headView = LayoutInflater.from(this).inflate(R.layout.news_item_toutiao_detail_header,null);
        webView =(ProgressWebView) headView.findViewById(R.id.item_progressWebView);
        webView.setFocusable(false);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setJavaScriptEnabled(true);

        tv_ckqw =(TextView) headView.findViewById(R.id.tv_ckqw);
        tv_item_news_title =(TextView) headView.findViewById(R.id.tv_item_news_title);
        tv_item_news_time =(TextView) headView.findViewById(R.id.tv_item_news_time);
        rl_ad_top =(RelativeLayout) headView.findViewById(R.id.rl_ad_top);
        fl_ad_top =(FrameLayout) headView.findViewById(R.id.fl_ad_top);
        CSJADTools.loadCSJAdMiddleBanner(this,rl_ad_top,"",CSJ_BANNER_ONE_ID,375,90);
        GDTADTools.loadHFAdByID(getContext(),fl_ad_top,GDT_APP_MB_PIC_TWO,375,0 );
        touTiaoChildRecycleAdapter.addHeaderView(headView);
        tv_ckqw.setOnClickListener(v -> {
            float   contentHeight = webView.getContentHeight() *  webView.getScale() ;
            int mWebViewTotalHeight =(int) (contentHeight- webView.getHeight());
            Log.d("appwe ","appweb=上下可滚动的范围="+mWebViewTotalHeight+"");
            Log.d("appwe","b=获取html高度="+webView.getContentHeight()+"");
            Log.d("appweb","=手机上网页缩放比例="+webView.getScale()+"");
            Log.d("appweb=w=",webView.getHeight()+"");
            RelativeLayout.LayoutParams linearParams = (RelativeLayout.LayoutParams) webView.getLayoutParams();
            linearParams.height = webView.getHeight()+ Math.abs(mWebViewTotalHeight);
            webView.setLayoutParams(linearParams);
            tv_ckqw.setVisibility(View.GONE);
        });
        touTiaoChildRecycleAdapter.setItemDAtaClink(this::itemViewclink);


    }
    @Override
    public void itemViewclink(String timea, String url, String title, String describe, String valueString) {
        initCSJAD();
        if(!UIUtils.isEmpty(url)){
            if(url.contains(".html")){
                Bundle bundle = new Bundle();
                bundle.putString("news_form_time",timea+"");
                bundle.putString("newsID",url);
                bundle.putString("newsTitle",title+"");
                bundle.putString("newsDescribe",describe+"");
                bundle.putString("value", value+"");
                ARouter.getInstance().build(RouterConfig.ROUTER_ACTIVITY_NEWS_TOUTIAO_DETAIL_OTHER).with(bundle).navigation();
            }else {
                Bundle bundle = new Bundle();
                bundle.putString("url",url);
                bundle.putString("title",title);
                bundle.putString("type","微信头条");
                ARouter.getInstance().build(RouterConfig.ROUTER_ACTIVITY_WEB).with(bundle).navigation();
            }

        }
    }

    private void initViewData(){
        StatusBarUtils.with(this,false)
                .setIsActionBar(false)
                .clearActionBarShadow()
                .setDrawable(getResources().getDrawable(R.drawable.sys_color_two))
                .init();
        dataBinding.bindSysToolBar.toolBarTvTitle.setText("资讯详情");

        mViewModel.touTiaoContentBean.observe(this,touTiaoContentBean->{
            if(!UIUtils.isEmpty(touTiaoContentBean) && !UIUtils.isEmpty(touTiaoContentBean.getNewslist())){
                if(mViewModel.isReFlash){
                    touTiaoChildRecycleAdapter.setNewData(touTiaoContentBean.getNewslist());
                }else {
                    touTiaoChildRecycleAdapter.addData(touTiaoContentBean.getNewslist());
                    touTiaoChildRecycleAdapter.loadMoreComplete();
                }
            }
        });
    }


    @JavascriptInterface
    public void resize(final float height) {
        TouTiaoDetailActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                webView.setLayoutParams(new LinearLayout.LayoutParams(getResources().getDisplayMetrics().widthPixels, (int) (height * getResources().getDisplayMetrics().density)));
            }
        });
    }


    private void initClink(){
        dataBinding.bindSysToolBar.toolBarIvBack.setOnClickListener(v -> finish());

        //看视频
        dataBinding.ivSpz.setOnClickListener(v -> {
            if(UIUtils.isOpenAD()) prepareVideo();//准备视频播放
        });

        dataBinding.recyclerChild.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Log.d("nestedScrollView",dy+"滚动了");
                if (!recyclerView.canScrollVertically(-1)) { // 到达顶部
                    if(!UIUtils.isEmpty(rl_ad_top) && scrollNum>0) {
                        CSJADTools.loadCSJAdMiddleBanner(getContext(),rl_ad_top,"",CSJ_BANNER_ONE_ID,375,90);
                        GDTADTools.loadHFAdByID(getContext(),fl_ad_top,GDT_APP_MB_PIC_TWO,375,0 );
                    }

                }
                if (Math.abs(dy-oldScrollY)>10 ) {//是否滚动
                    if(!isMoving) setAnimation();
                }else {
                    oldScrollY = dy;
                }
            }
        });
    }

    //任务动画
    private void setAnimation() {
        isMoving =true;
        scrollNum++;
        if(scrollNum<scrollMaxNum){
            if(scrollNum ==0 && scrollEndY==0){
                scrollStartY = 0;
                scrollEndY = 100/scrollMaxNum;
            }else{
                scrollStartY = scrollEndY;
                scrollEndY = (100/scrollMaxNum ) * scrollNum;
            }
        }else{
            scrollStartY = scrollEndY;
            scrollEndY = 100;
        }
        if(scrollStartY ==100){
            submitTask();
        }else{
            ValueAnimator animator =  ValueAnimator.ofInt(scrollStartY, scrollEndY).setDuration(2500);
            animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    if (animation != null) {
                        int currentValue = (int) animation.getAnimatedValue();
                        Log.d("setAnimation",currentValue+"==="+scrollEndY+"==="+scrollStartY);
                        dataBinding.circularProgressView.setProgress(currentValue);
                        if(currentValue >=scrollEndY) isMoving = false;
                        if(currentValue>=100) submitTask();
                    }
                }
            });
            animator.start();
        }
    }

    /**
     * 提交任务
     */
    private void submitTask(){
        if(!isSubmitTask){
            isSubmitTask = true;
            mViewModel.readMoney(TouTiaoDetailActivity.this);
        }
    }

    private String getHtmlData(String bodyHTML) {
        String head = "<head>" +
                "   <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0\"/>" +
                "   <style> " +
                "       *{font-size: 14px; color: #404040;} " +
                "       img{max-width: 100%; width:auto; height: auto;}" +
                "   </style>" +
                "</head>";
        return "<html>" + head + "<body>" + bodyHTML + "</body></html>";
    }


    @Override
    public void onLoadMoreRequested() {
        getNewsPageData(false);
    }

}
